package org.ala.tcp_feign_client.spring.feign.results.impl;

import org.ala.tcp_feign_client.context.TcpFeignClientContext;
import org.ala.tcp_feign_client.spring.feign.results.IBizRespResultCallback;
import org.ala.tcp_feign_client.spring.feign.results.ITcpFeignClientResultsMapper;
import org.ala.tcp_feign_common.exceptions.SerializableException;
import org.ala.tcp_feign_common.msg.biz_resp.BizRespByteMessage;
import org.ala.tcp_feign_common.msg.biz_resp.body.BizRespBody;

/**
 *
 * @author 骆毅(ala)
 * @date 2024年4月24日
 */
public abstract class AbstractBizRespResultCallback implements IBizRespResultCallback {

	
	/**
	 * 回调对应的msgId
	 */
	protected long msgId;
	/**
	 * 回调的超时时间
	 */
	protected long timeout;
	/**
	 * 是否已完成
	 */
	protected boolean finished = false;
	/**
	 * 开始等待时间戳
	 */
	protected long bindTimestamp;
	/**
	 * 
	 */
	protected ITcpFeignClientResultsMapper resultsMapper;
	
	
	public AbstractBizRespResultCallback(long msgId, long timeout, ITcpFeignClientResultsMapper resultsMapper) {
		this.msgId = msgId;
		this.timeout = timeout;
		this.resultsMapper = resultsMapper;
	}
	
	
	@Override
	public long msgId() {
		return msgId;
	}
	@Override
	public boolean isFinished() {
		return finished;
	}
	@Override
	public long bindTimestamp() {
		return bindTimestamp;
	}


	@Override
	public final void doCallback(BizRespByteMessage msg) throws SerializableException {
		finished = true;
		triggeCallback(msg);
	}
	protected abstract void triggeCallback(BizRespByteMessage msg) throws SerializableException;


	@Override
	public final void doTimeout() {
		resultsMapper.unbind(msgId);
		triggeTimeout();
	}
	protected abstract void triggeTimeout();


	/**
	 * 构建返回值
	 * @throws SerializableException 
	 */
	protected Object buildResp(BizRespByteMessage msg) throws SerializableException {
		BizRespBody resp = TcpFeignClientContext.instance().getSerializabler().deSerialize(msg.getBody(), BizRespBody.class);
		return resp.getResult();
	}


	public void setBindTimestamp(long bindTimestamp) {
		this.bindTimestamp = bindTimestamp;
	}
	
}
